#!/usr/bin/perl -w
#
# Show the content of a record
#

use strict;

use Counter;
use FileTable;
use Getopt::Long;
use Algorithm::Diff;


use vars qw{$file $recno $key $rec $table $field $showhistory};

GetOptions(
	   "history" => \$showhistory,
	   );


$file = shift(@ARGV);
$recno = shift(@ARGV);
$key = shift(@ARGV);

$table = Counter::openfile("$file");
if ($key) {
    $field = $recno;
    $rec = $table->getbykey($field, $key);
    if ($rec) {
	$recno = $rec->key;
    } else {
	warn  "$file: Field value $field:$key not found\n";
	undef $recno;
    }
} else {
    $rec = $table->get($recno);
    warn "$file: Record number $recno not found\n" if !$rec;
}

if ($rec) {
    print "==== $file record $recno ====\n";
    for $key (sort($rec->fields())) {
	my $val = $$rec{$key};
	$val =~ s/\n/\n    /g;
	print "$key:$val\n" unless $key =~ /^\*/;
    }
}
if ($showhistory && $recno) {
    print "----- History ----\n";
    my ($ev, $field);
    my (@hist, %save);
    @hist = FileTable::Log::history($file, $recno);
    for $ev (@hist) {
	$$ev{date} = ".undated" if !$$ev{date};
    }
    for $ev (sort {$$a{date} cmp $$b{date}} @hist) {
	print "$$ev{date}: $$ev{tablename} ($$ev{operation} $$ev{authority})\n";
	printdiff($save{$$ev{tablename}}, $$ev{data}); 
	$save{$$ev{tablename}} = $$ev{data};
	print "\n";
    }
}

sub printdiff {
    my ($old, $new) = @_;

    if (!$old) {
	$new =~ s/(^|\n)/$1N /g;
	print $new;
    } else {
	my @old = sort(split(/\n/, $old));
	my @new = sort(split(/\n/, $new));
	my @diffs = Algorithm::Diff::diff(\@old, \@new);
	my $hunk;
	for $hunk (@diffs) {
	    my $chg;
	    for $chg (@$hunk) {
		next if $$chg[2] =~ /^f_mtime/; # superfluous
		print $$chg[0], " ", $$chg[2], "\n",
	    }
	}
    }
}
